package dao;


import org.snowin.common.SessionData;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SmsDao  extends BaseDao
{
    public SmsDao(SessionData sessionData)
    {
        super(sessionData);
    }

    public long getLatestId()
    {
        long id = 0L;
        ResultSet rs = null;
        try
        {
            rs = executeSql("select iAutoID from smstable limit 1");
            while (rs.next()) {
                id = Long.parseLong(rs.getString("iAutoID"));
            }
            return id;
        }
        catch (SQLException e)
        {
            this.logger.info("Get ID from DB failed", e);
        }
        finally
        {
            try
            {
                if (null != rs) {
                    rs.close();
                }
            }
            catch (SQLException e)
            {
                this.logger.info("Close the result set connection failed", e);
            }
        }
        return  0L;
    }

    public ResultSet getLatestRecord()
    {
        ResultSet rs = null;
        String[] recordArray = new String[2];
        try
        {
            rs = executeSql("select * from  tmstable order by iAutoID desc limit 1");
            while (rs.next())
            {
                recordArray[0] = (Long.parseLong(rs.getString("iAutoID")) + "");
                recordArray[1] = (Long.parseLong(rs.getString("sMessage")) + "");
            }
            return rs;
        }
        catch (Exception e)
        {
            this.logger.info("Get latest Record failed");
        }
        finally
        {
            try
            {
                if (null != rs) {
                    rs.close();
                }
            }
            catch (SQLException e)
            {
                this.logger.info("Close the result set connection failed", e);
            }
        }
        return  null;
    }

    public ResultSet executeSql(String sql)
    {
        ResultSet rs = null;
        try
        {
            Statement stmt = this.conn.createStatement();

            rs = stmt.executeQuery(sql);
        }
        catch (SQLException e)
        {

            this.logger.info("execute the sql failed", e);
            return null;
        }

        return rs;
    }

    public void closeConnection()
    {
        try
        {
            this.conn.commit();
            this.conn.close();
        }
        catch (Exception e)
        {
            this.logger.info("Close DB connection failed", e);
        }
    }
}
